package admin_controller

import (
	"cloud-navigation/app/common/request"
	"cloud-navigation/app/common/response"
	"cloud-navigation/app/models"
	"cloud-navigation/app/services"
	"cloud-navigation/global"
	"cloud-navigation/utils"

	"github.com/gin-gonic/gin"
)

// 获取系统设置
func GetSystem(c *gin.Context) {
	var sys models.System
	err := global.App.DB.First(&sys).Error
	if err != nil {
		response.BusinessFail(c, err.Error())
		return
	}
	response.Success(c, sys)
}

// 保存系统设置
func SaveSystem(c *gin.Context) {
	var (
		sys     request.SystemRequest
		system  models.System
		delLogo = ""
	)
	if !services.Request(c, &sys) {
		return
	}
	db := global.App.DB
	db.First(&system)

	if system.Logo != sys.Logo {
		delLogo = system.Logo
	}

	system.Beian = sys.Beian
	system.Name = sys.Name
	system.Logo = sys.Logo
	system.Status = sys.Status
	if sys.Keywords != "" {
		system.Keywords = sys.Keywords
	}
	err := db.Save(&system).Error
	if err != nil {
		response.BusinessFail(c, err.Error())
		return
	}
	if delLogo != "" {
		utils.DeleteFile(delLogo)
	}
	services.WriteLogs(c, "修改系统设置", 0)
	response.Success(c, system)
}

func UploadLogo(c *gin.Context) {
	file, _ := c.FormFile("file")
	if file.Size >= 10<<20 {
		response.BusinessFail(c, "上传文件最大10MB")
		return
	}
	pa, err := utils.SaveUploadedFile(c, file, "local", "")
	if err != nil {
		response.BusinessFail(c, err.Error())
		return
	}
	response.Success(c, pa)
}
